import { requestConfig } from '@/config'

const { responseEnum } = requestConfig

export class RequestInterceptor {
  onFulfilled(config) {
    // @todo 根据业务调整对应请求拦截逻辑, 如添加token, 重复请求校验等
    console.log('RequestInterceptor config:', config)
    if(config.method === 'get' && !config.data) {
      // get请求默认添加data字段以绕过axios自动清空请求头中的Content-Type
      config.data = true
    }
    return config
  }

  onRejected(error) {
    return Promise.reject(error)
  }

  options = {
    synchronous: false,
    runWhen: (config) => {
      if(config.skipReqIntercept) {
        return false
      }
      return true
    },
  }
}

export class ResponseInterceptor {
  onFulfilled(response) {
    const { data: axiosResData, status, request } = response
    // eslint-disable-next-line no-unused-vars, unused-imports/no-unused-vars
    let { code, data, msg, succuss } = axiosResData
    // 响应包装未设置状态码则默认成功状态
    code = code || status

    const responseMatch = Object.values(responseEnum).find(item => item.code === code)
    // 获取错误信息
    const message = responseMatch?.msg || msg || responseEnum.default.msg
    // 二进制数据则直接返回
    if(request.responseType === 'blob' || request.responseType === 'arraybuffer') {
      return axiosResData
    }
    switch (code) {
      // @todo 根据业务调整对应逻辑, 如弹出确认窗、跳转登录、清空token等
      case responseEnum.success.code:
        // 不从此处直接return
        break
      case responseEnum.tokenExpired.code:
      case responseEnum.tokenInvalid.code:
      case responseEnum.notFound.code:
      case responseEnum.serverError.code:
        window.$msg.error(message, { duration: 1000 })
        return Promise.reject(new Error(message))
      default:
        // 其他未定义均视为异常情况处理, 弹出Notification提示
        window.$notice.error({
          title: '未知异常',
          content: message,
          duration: 3000,
        })
        return Promise.reject(new Error(message))
    }

    return axiosResData
  }

  onRejected(error) {
    let { message } = error
    if(message === 'Network Error') {
      message = '后端接口连接异常'
    }
    else if(message.includes('timeout')) {
      message = '系统接口请求超时'
    }
    else if(message.includes('Request failed with status code')) {
      message = `系统接口${message.substr(message.length - 3)}异常`
    }
    window.$msg.error(message, { duration: 5000 })
    return Promise.reject(error)
  }
}
